import { encryptPassword, makeSalt } from "../../utils/cryptogram";
import { UserExistService } from "./user.exist.service";
import { Injectable } from "@nestjs/common";
import sequelize from "../../database/sequelize";

@Injectable()//表示类可以被当作依赖被注入
export class UserRegisterService {
  //依赖注入
  constructor(private userExistService: UserExistService) {
  }

  async userRegister(requestBody: any): Promise<any> {
    let nickName: string = requestBody.nickName;
    let phoneNum: string = requestBody.phoneNum;
    let password: string = requestBody.password;
    let confirmPW: string = requestBody.confirmPW;
    if (password !== confirmPW) {
      return {
        code: 400,
        msg: "确认密码与密码不一致！"
      };
    }
    const user = await this.userExistService.userExist({ nickName, phoneNum });
    if (user){
      if (user.phoneNum == phoneNum) {
        return {
          code: 400,
          msg: "该手机号已被注册！"
        };
      } else{
        return {
          code: 400,
          msg: "该昵称已被占用！"
        };
      }
    }
    let PWSalt = makeSalt();
    let hashPW = encryptPassword(password, PWSalt);
    let sql =
      `INSERT INTO userRegister 
        (nickName,phoneNum,PWSalt,hashPW)
        VALUES
        ('${nickName}','${phoneNum}','${PWSalt}','${hashPW}')`;
    try {
      await sequelize.query(sql, { logging: false });
      return {
        code: 200,
        msg: "注册成功！"
      };
    } catch (error) {
      return {
        code: 503,
        msg: `服务器异常：${error}`
      };
    }
  }
}